<template>
  <div id="manager-user">
    <el-container style="height: 100vh; border: 1px">
      <!-- 头部信息 -->
      <el-header>
        <HeaderBar></HeaderBar>
      </el-header>
      <el-container style="flex: 1; display: flex;">
        <!-- 左侧栏 -->
        <el-aside :width="sidebarWidth" style="transition: width 0.3s ease;">
          <Sidebar @sidebar-toggle="handleSidebarToggle"></Sidebar>
        </el-aside>
        <!-- 主体内容区 -->
        <el-main :style="{
          marginLeft: '0',
          transition: 'margin-left 0.3s ease',
          width: `calc(100% - ${sidebarWidth})`
        }">
          <el-row class="search">
            <input class="relative" v-model="searchKeyword" type="text" placeholder="搜索用户..." @input="handleSearchInput"
              @focus="isSearchFocused = true" @blur="isSearchFocused = false">
            <el-select v-model="selectedUserType" placeholder="选择用户类型" @change="handleUserTypeChange">
              <el-option label="求职者" value="seeker"></el-option>
              <el-option label="企业用户" value="recruiter"></el-option>
              <el-option label="管理员" value="admin"></el-option>
            </el-select>
            <el-button class="add-button" @click="addManager" :disabled="!isSuperAdmin">
              添加管理员
            </el-button>
          </el-row>

          <!-- 信息列表 -->
          <div class="table-scroll-container">
            <el-table :data="tableData" class="user-table" style="width: 100%">
              <el-table-column label="用户信息" width="240">
                <template slot-scope="scope">
                  <div class="user-info-row">
                    <img :src="scope.row.avatar || defaultAvatar" class="user-avatar">
                    <span class="user-name">{{ scope.row.name }}</span>
                  </div>
                </template>
              </el-table-column>
              <el-table-column prop="phone" label="电话" width="240"></el-table-column>
              <!-- <el-table-column v-if="scope.row.stype === 'seeker'" prop="education" label="学历" width="240"></el-table-column> -->
              <el-table-column label="用户类型" width="240">
                <template slot-scope="scope">
                  <span class="user-type-badge" :class="getUserTypeClass(scope.row)">{{
                    getUserTypeText(scope.row) }}</span>
                </template>
              </el-table-column>
              <el-table-column label="详细信息" width="220">
                <template slot-scope="scope">
                  <el-button size="mini" type="primary" icon="el-icon-info" plain
                    @click="openResumeDialog(scope.row)"></el-button>
                </template>
              </el-table-column>
            </el-table>
          </div>

          <!-- 分页控件 -->
          <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange"
            :current-page="currentPage" :page-sizes="[5, 10, 20]" :page-size="pageSize"
            layout="total, sizes, prev, pager, next, jumper" :total="totalCount" class="custom-pagination">
          </el-pagination>

          <!-- 弹窗组件 -->
          <UserResumeDialog :visible.sync="resumeDialogVisible" :user="currentUser" :defaultAvatar="defaultAvatar"
            class="userDialog" @refreshUserList="refreshUserList">
          </UserResumeDialog>
          <AddManagerDialog :visible.sync="addManagerDialogVisible" @refreshUserList="refreshUserList">
          </AddManagerDialog>
        </el-main>
      </el-container>
    </el-container>
  </div>
</template>

<script>
import Sidebar from "@/components/ManagerSidebar.vue";
import HeaderBar from "@/components/ManagerHeaderBar.vue";
import UserResumeDialog from "../components/ManaUserDialog.vue";
import AddManagerDialog from "../components/addManager.vue";
import { mapGetters } from 'vuex';
import { getManagers } from '@/util/manager_api/manager';
import { getSeekers } from "@/util/manager_api/seeker";
import { getRecruiters } from "@/util/manager_api/recruiter";
import debounce from 'lodash/debounce';

export default {
  components: {
    Sidebar,
    HeaderBar,
    UserResumeDialog,
    AddManagerDialog
  },
  computed: {
    ...mapGetters('manager', ['isSuperAdmin']),
    sidebarWidth() {
      return this.isSidebarCollapsed ? '60px' : '200px';
    }
  },
  data() {
    return {
      isSearchFocused: false,
      searchKeyword: '',
      selectedUserType: "admin",
      tableData: [],
      defaultAvatar: 'https://picsum.photos/200/200?random=100',
      resumeDialogVisible: false,
      currentUser: {},
      addManagerDialogVisible: false,
      loading: false,
      debouncedSearch: null,
      isSidebarCollapsed: false,
      currentPage: 1,
      pageSize: 5,
      totalCount: 0
    };
  },
  created() {
    // 初始化防抖搜索
    this.debouncedSearch = debounce(async () => {
      // 避免空关键词频繁请求
      if (!this.searchKeyword.trim() && this.tableData.length > 0) {
        return;
      }
      this.currentPage = 1;
      await this.fetchCurrentPageData();
    }, 300);

    // 初始化加载数据
    this.fetchCurrentPageData();
  },
  beforeDestroy() {
    //组件销毁时清除防抖定时器，避免内存泄漏
    this.debouncedSearch.cancel();
  },
  methods: {
    handleSearchInput() {
      // 立即清空旧数据
      if (!this.searchKeyword.trim()) {
        this.tableData = [];
      }
      // 触发防抖搜索
      this.debouncedSearch();
    },

    // 获取用户数据
    async fetchCurrentPageData() {
      if (this.loading) return;

      this.loading = true;
      this.tableData = [];  // 清空旧数据，避免显示混淆

      try {
        const params = {
          page: this.currentPage,
          size: this.pageSize,
          content: this.searchKeyword || ''  // 确保关键词正确传递
        };

        let response, list;

        // 根据用户类型请求对应接口
        switch (this.selectedUserType) {
          case 'admin':
            response = await getManagers(params);
            list = response.data.data.respList.map(item => ({ ...item, stype: 'admin' }));
            break;
          case 'seeker':
            response = await getSeekers(params);
            list = response.data.data.respList.map(item => ({ ...item, stype: 'seeker' }));
            break;
          case 'recruiter':
            response = await getRecruiters(params);
            list = response.data.data.respList.map(item => ({ ...item, stype: 'recruiter' }));
            break;
          default:
            throw new Error('未知用户类型');
        }

        if (response.data.code !== 201) {
          throw new Error(`接口错误: ${response.data.message || '未知错误'}`);
        }

        this.tableData = list;
        this.totalCount = response.data.data.total;

        if (this.searchKeyword && list.length === 0) {
          this.$message.warning(`未找到包含"${this.searchKeyword}"的用户`);
        }

      } catch (error) {
        console.error('获取用户列表失败:', error);
        this.$message.error(`搜索失败: ${error.message || '请重试'}`);
        this.tableData = [];
      } finally {
        this.loading = false;
      }
    },


    // 用户类型变更处理
    handleUserTypeChange() {
      this.currentPage = 1;
      this.debouncedSearch.cancel();
      this.fetchCurrentPageData();
    },

    // 添加管理员
    addManager() {
      if (!this.isSuperAdmin) {
        this.$message.warning('只有超级管理员才能添加新管理员');
        return;
      }
      this.addManagerDialogVisible = true;
    },

    // 刷新用户列表
    refreshUserList() {
      this.fetchCurrentPageData();
    },

    // 打开详情弹窗
    openResumeDialog(row) {
      this.resumeDialogVisible = true;
      this.currentUser = row;
    },

    // 修复用户类型文本显示逻辑
    getUserTypeText(row) {
      const { stype } = row || {};

      // 管理员类型细分（优先级最高）
      const managerTypes = {
        'SUPER': '超级管理员',
        'NORMAL': '普通管理员'
      };

      // 通用用户类型
      const userTypes = {
        'seeker': '求职者',
        'recruiter': '企业用户',
        'admin': '管理员'
      };

      // 企业内部职位类型
      const positionTypes = {
        'BOSS': '老板',
        'MANAGEMENT': '管理层',
        'RECRUITER': '招聘人员'
      };

      // 判断管理员细分类型
      if (stype === 'admin') {
        return managerTypes[row.managerType];
      } else if (stype === 'recruiter') {
        return positionTypes[row.type];
      } else if (stype === 'seeker') {
        return userTypes[stype];
      } else {
        return '未知类型';
      }
    },

    // 获取用户类型样式类
    getUserTypeClass(row) {
      const { stype } = row || {};
      const classMap = {
        'seeker': 'seeker-badge',
        'recruiter': 'recruiter-badge',
        'admin': 'admin-badge'
      };
      return classMap[stype] || '';
    },

    // 分页事件处理
    handleSizeChange(newSize) {
      this.pageSize = newSize;
      this.currentPage = 1;
      this.fetchCurrentPageData();
    },

    handleCurrentChange(newPage) {
      this.currentPage = newPage;
      this.fetchCurrentPageData();
    },

    // 侧边栏切换
    handleSidebarToggle(isCollapsed) {
      this.isSidebarCollapsed = isCollapsed;
    }
  }
};
</script>

<style scoped>
@import url('./ManaUserViews.css')
</style>